/**
 * Created by zhouli on 18/10/23
 * 针对报表的特殊组件
 * 选择 费用类型 组件，组件依赖于账套id
 *
 * 重构成advanced-area时没有做这些组件的重构，只是拿过来改造了一下
 */
import React from 'react';
import { Modal, Input, Icon, Button, Table, Popover, Badge } from 'antd';
import { deepFullCopy, messages } from 'share/common';
import ETSFRService from './expense-type-select-for-report.service';
import 'styles/data-center/report/travel-report/components/expense-type-select-for-report/expense-type-select-for-report.scss';
import SelectSupporter from "../select-supporter";

class ExpenseTypeSelectForReport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      columns: [
        {
          title: messages('finance-7.key253')/*名称*/,
          dataIndex: "name",
          width: '40%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('finance-7.key247')/*编码*/,
          dataIndex: "code",
          width: '20%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'enabled',
          width: '20%',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('finance-7.key248')/*启用temp*/ : messages('finance-7.key249')/*禁用temp*/}/>)
        },
      ],
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,//费用类型不多，根据其他使用场景，全部加载，前端搜索
      },
      loading: false,
      data: [],
      copyData: [],//前端搜索使用
      rowSelection: {
        type: this.props.multiple ? 'checkbox' : 'radio',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      costCenter: {},
      selectedData: [],  //已经选择的数据项
      expenseTypeName: "",//关键字搜索
      selectedDataCache: [],  // 缓存当前已选项，因为在点击table中的项的时候，这个值已经改变，但是点击取消的时候又需要还原
      selectedRowKeysCache: [],  // 缓存当前已选RowKeys，因为在点击table中的项的时候，这个值已经改变，但是点击取消的时候又需要还原
    };
  }

  componentWillReceiveProps(nextProps) {
    const { value, setOfBooksId } = nextProps;
    const { rowSelection } = this.state;

    // 外部清空
    if ((!value || setOfBooksId !== this.props.setOfBooksId) && rowSelection.selectedRowKeys.length) {
      this.onClear();
    } else {
      if (value && value.length) {
        this.onSelectChange(value.map(item=>item.id), value)
      }
    }
  }

  //选项改变时的回调，重置selection
  //点击 title 行
  onSelectChange = (selectedRowKeys, selectedRows) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    if (!this.props.multiple) {
      this.setState({ rowSelection });
    } else {
      this.setState({
        rowSelection,
        selectedData: selectedRows
      });
    }
  };
  //点击数据行
  onSelectItem = (record, selected) => {
    if (!this.props.multiple) {
      let selectedData = [];
      if (selected) {
        selectedData.push(record);
        this.setState({ selectedData });
      }
    }
  };
  handleRowClick = (record) => {
    let id = record.id;
    let { rowSelection, selectedData } = this.state;
    if (this.props.multiple) {
      let hasIndex = _hasInArr(id, rowSelection.selectedRowKeys);
      if (hasIndex === 0 || hasIndex > 0) {
        selectedData.splice(hasIndex, 1);
        rowSelection.selectedRowKeys.splice(hasIndex, 1);
      } else {
        selectedData.push(record);
        rowSelection.selectedRowKeys.push(id);
      }
      this.setState({
        selectedData,
        rowSelection
      });
    } else {
      if (_hasInArrSingle(id, rowSelection.selectedRowKeys)) {
        selectedData = [];
        rowSelection.selectedRowKeys = [];
      } else {
        selectedData = [record];
        rowSelection.selectedRowKeys = [id];
      }
      this.setState({
        selectedData,
        rowSelection
      });
    }

    function _hasInArrSingle(id, arr) {
      if (arr.length > 1) {
        return arr[0] === id;
      } else {
        return false;
      }
    }

    function _hasInArr(id, arr) {
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] === id) {
            return i;
          }
        }
        return false;
      } else {
        return false;
      }
    }
  };
  //查询所有成本中心项通过成本中心oid
  getExpenseTypeListByBooksID = (setOfBooksId) => {
    if (!setOfBooksId) {
      return;
    }
    this.setState({
      loading: true,
    });
    return ETSFRService.getExpenseTypeListByBooksID(setOfBooksId)
      .then((res) => {
        this.setState({
          loading: false,
          data: res.data,
          copyData: deepFullCopy(res.data)
        })
      });
  };

  //显示模板
  showModel = () => {
    const { setOfBooksId } = this.props;
    const { rowSelection, selectedData, loading } = this.state;
    if (loading || !setOfBooksId) return;
    this.getExpenseTypeListByBooksID(setOfBooksId).then(() => {
      this.setState({
        visible: true,
        costCenterItemName: "",//关键字搜索
        selectedRowKeysCache: [...rowSelection.selectedRowKeys],
        selectedDataCache: [...selectedData]
      }, () => {
        this.onChangeExpenseTypeName();
      })
    })
  };

  onClear = () => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({
      selectedData: [],
      rowSelection
    });
    this.props.onChange(undefined)
  };

  handleCancel = () => {
    let { rowSelection, selectedDataCache, selectedRowKeysCache } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeysCache;
    this.setState({
      selectedData: selectedDataCache,
      rowSelection,
      visible: false
    });
  };

  handleOk = () => {
    this.setState({
      visible: false
    });
    let { selectedData } = this.state;
    if (selectedData.length > 0) {
      if (this.props.multiple) {
        this.props.onChange(selectedData);
      } else {
        this.props.onChange(selectedData[0]);
      }
    } else {
      this.props.onChange(undefined);
    }
  };
  //搜索成本中心项
  emitEmptyForDep = () => {
    this.userNameInput.focus();
    this.setState({ expenseTypeName: '' }, () => {
      this.onChangeExpenseTypeName();
    });
  };

  //分页点击（前端翻页）
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    })
  };
  //搜索成本中心项(前端搜索)
  onChangeExpenseTypeName = (e) => {
    let expenseTypeName = "";
    if (e) {
      expenseTypeName = e.target.value;
    }
    let originData = this.state.copyData;
    let filterData = [];
    originData.map(item => {
      if (item.name.match(expenseTypeName) || item.code.match(expenseTypeName)) {
        filterData.push(item);
      }
    });
    this.setState({
      expenseTypeName,
      data: filterData,
    });
  };

  getShowValue = () => {
    let { selectedData } = this.state;
    let { setOfBooksId } = this.props;
    if (setOfBooksId && selectedData.length > 0) {
      return (selectedData.map(item => item.name)).join();
    } else {
      return undefined
    }
  };

  getPlaceholder = () => {
    let { setOfBooksId } = this.props;
    if (setOfBooksId) {
      return messages('common.select')/*请选择*/;
    } else {
      return messages('finance-7.key154')/*请先选择账套*/;
    }
  };

  render() {
    let { columns, data, pagination, loading, rowSelection, expenseTypeName, visible } = this.state;
    let { title } = this.props;
    const suffix = expenseTypeName ? <Icon type="close-circle" onClick={this.emitEmptyForDep}/> : null;
    let showValue = this.getShowValue();
    const placeholder = this.getPlaceholder();
    return (
      <div className="expense-type-select-for-report">
        <div>
          <SelectSupporter
            value={showValue}
            placeholder={placeholder}
            onFocus={this.showModel}
            onClear={this.onClear}
          />
        </div>

        <Modal
          width={800}
          className="expense-type-select-for-report-modal"
          title={messages('common.select')/*请选择*/ + title}
          closable={false}
          visible={visible}
          footer={[
            <Button key="back"
                    onClick={this.handleCancel}>
              {messages('common.cancel')/*取消*/}
            </Button>,
            <Button key="submit"
                    type="primary"
                    onClick={this.handleOk}>
              {messages('common.ok')/*确定*/}
            </Button>,
          ]}
        >
          <div>
            <div className="cost-center-item-wrap">
              <div className="table-header-inp f-right">
                <Input
                  className='cost-center-item-name-search'
                  key={'costCenterItemName-search'}
                  placeholder={messages('finance-7.key254')/*输入费用类型名称/编码搜索*/}
                  prefix={<Icon type="search" className='font-disabled'/>}
                  suffix={suffix}
                  value={expenseTypeName}
                  onChange={this.onChangeExpenseTypeName}
                  ref={node => this.userNameInput = node}
                />
              </div>
              <div className="clear"/>
            </div>
            <div className="table-wrap">
              <Table columns={columns}
                     dataSource={data}
                     pagination={pagination}
                     loading={loading}
                     rowKey="id"
                     bordered
                     onRow={record => ({ onClick: () => this.handleRowClick(record) })}
                     rowSelection={rowSelection}
                     onChange={this.onChangePager}
                     size="middle"/>
            </div>
          </div>
        </Modal>

      </div>
    );
  }
}

ExpenseTypeSelectForReport.propTypes = {
  multiple: React.PropTypes.bool,//是否多选
  onChange: React.PropTypes.func.isRequired,// 点击确认之后的回调：返回结果
  title: React.PropTypes.any.isRequired,//字段标题
  setOfBooksId: React.PropTypes.any,//账套id，需要有账套id查询成本中心
};

ExpenseTypeSelectForReport.defaultProps = {
  title: messages('common.expense.type')/*费用类型*/,//由外面传入
  setOfBooksId: null,
  multiple: false,
};


export default ExpenseTypeSelectForReport;



